/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class code6 {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        if(root == null) {
            return ret;
        }
        Stack<TreeNode> st = new Stack<>();

        TreeNode cur = root;
        while(cur!=null || !st.isEmpty()) {
            if(cur != null) {
                st.push(cur);
                ret.add(cur.val);
                cur = cur.left;
            } else {
                cur = st.pop().right;
            }
        }
        return ret;
    }
}